const path = require('path')
const fs = require('fs');
const { getVersion, getRevision } = require('./buildutils');

const config = {
  host: 'xxx.xxx.xxx.xxx',
  port: 22,
  username: 'root',
  password: 'xxx'
}

function gulptasksUpload($, gulp, buildFolder){
  const gulpSsh = new $.ssh({
    ignoreErrors: false,
    sshConfig: config
  })

  gulp.task('configChangeToBuild', cb => {
    const configUrl = path.join('..', 'manifest.json');
    let configContent = fs.readFileSync(configUrl).toString();
    const version = getVersion();
    const revision = getRevision();
    configContent = configContent.replace('%versionCode%', parseInt(version.replace(/\./g, '')) + 1000);
    configContent = configContent.replace('%versionName%', version);
    fs.writeFileSync(path.join(buildFolder, 'manifest.json'), configContent)
    cb();
  })

  gulp.task('deleteServerWgt', () => {
    return gulpSsh.shell('rm -rf /www/wwwroot/download/xiuxian.wgt');
  })

  gulp.task('deleteServerFolder', () => {
    return gulpSsh.shell('rm -rf /www/wwwroot/xiuxian');
  })

  gulp.task('uploadServerWgt', cb => {
    const wgtPath = path.join(buildFolder, 'unpackage/release/H53A7F10F.wgt');
    if(fs.existsSync(wgtPath)){
      return gulp.src(wgtPath)
      .pipe($.rename('xiuxian.wgt'))
      .pipe(gulpSsh.dest('/www/wwwroot/download'))
    } else {
      cb();
    }
  })

  gulp.task('uploadServerApk', cb => {
    const apkPath = path.join('..', 'apk/H53A7F10F.apk');
    const apk2Path = path.join('..', 'apk/xiuxian.apk');
    if(fs.existsSync(apkPath)){
      return gulp.src(apkPath)
        .pipe($.rename('xiuxian.apk'))
        .pipe(gulpSsh.dest('/www/wwwroot/download'))
    } else if(fs.existsSync(apk2Path)){
      return gulp.src(apk2Path)
        .pipe(gulpSsh.dest('/www/wwwroot/download'))
    } else {
      cb();
    }
  })

  gulp.task('uploadServerFolder', () => {
    return gulp.src(['../server/**', '!../server/node_modules/**'], { nodir: true })
      .pipe(gulpSsh.dest('/www/wwwroot/xiuxian'))
  })

  gulp.task('uploadGameVersion', cb => {
    fs.writeFileSync(path.join('../server', 'version.json'), `{"version": "${getVersion()}"}`)
    cb();
  })

  gulp.task('reloadServer', () => {
    return gulpSsh.shell('cd /www/wwwroot/xiuxian && cnpm install && npm run start | pm2 reload xiuxian')
  })

  gulp.task('uploadServer', gulp.series('uploadServerFolder', 'reloadServer'))
}

module.exports = {
  gulptasksUpload,
}